<template>
  <div class="search-top">
    <a-row type="flex" justify="center">
      <!-- <a-col :span="6">
        <a-input placeholder="题目查询" v-model:value="searchStr" />
      </a-col>
      <a-col :span="1"></a-col>
      <a-col :span="2">
        <a-button type="primary" @click="search(1)">查询</a-button>
      </a-col>
      <a-col :span="1"></a-col>-->
      <a-col :span="2">
        <a-button type="primary" @click="addAll">新增</a-button>
      </a-col>
    </a-row>
  </div>
  <div class="list-table">
    <a-row type="flex" justify="center">
      <a-col :span="18">
        <a-table
          :columns="columns"
          :row-key="(record) => record.question_id"
          :data-source="dataSource"
          :pagination="false"
          :loading="loading"
          @change="handleTableChange"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.dataIndex === 'choice_info'">
              <span
                v-for="choice in record.choice_info"
                :key="choice"
              >{{ choice.title }} {{ choice.content }};</span>
            </template>
            <template v-if="column.dataIndex === 'action'">
              <span>
                <a @click="() => editAll(record.question_id, record)">修改</a>
                <a-divider type="vertical" />
                <a-popconfirm
                  title="确定删除?"
                  ok-text="确定"
                  cancel-text="取消"
                  @confirm="() => onDeleteAll(record.question_id)"
                >
                  <a href="javascript:;">删除</a>
                </a-popconfirm>
              </span>
            </template>
          </template>
        </a-table>
      </a-col>
    </a-row>
  </div>
  <div class="list-page">
    <a-row type="flex" justify="center">
      <a-col :span="18">
        <a-pagination
          v-model:current="pagination.current"
          v-model:pageSize="pagination.pageSize"
          :total="total"
          :showSizeChanger="false"
          @change="changePage"
        />
      </a-col>
    </a-row>
  </div>
  <a-modal
    v-model:visible="visible"
    width="1000px"
    title="题目管理"
    ok-text="确认"
    cancel-text="取消"
    @ok="onSubmit"
  >
    <a-form
      ref="formRef"
      :model="choosedData"
      :rules="rules"
      :label-col="labelCol"
      :wrapper-col="wrapperCol"
    >
      <a-form-item ref="question_desc" label="题目描述" name="question_desc">
        <a-input v-model:value="choosedData.question_desc" />
      </a-form-item>
      <a-form-item label="答案">
        <a-button
          type="primary"
          @click="handleAdd"
          v-if="choosedData.choice_info && choosedData.choice_info.length < 4"
        >新增选项</a-button>
        <a-table
          :columns="columns2"
          :data-source="choosedData.choice_info"
          bordered
          :pagination="false"
        >
          <template #bodyCell="{ column, text, record, index }">
            <template v-if="column.dataIndex === 'title'">
              <span>{{ titleArr[index] }}</span>
            </template>
            <template v-if="column.dataIndex === 'content'">
              <div class="editable-cell">
                <div v-if="editableData[record.key]" class="editable-cell-input-wrapper">
                  <a-input
                    v-model:value="editableData[record.key].content"
                    @pressEnter="save(record.key)"
                  />
                  <check-outlined class="editable-cell-icon-check" @click="save(record.key)" />
                </div>
                <div v-else class="editable-cell-text-wrapper">
                  {{ text || ' ' }}
                  <edit-outlined class="editable-cell-icon" @click="edit(record.key)" />
                </div>
              </div>
            </template>
            <template v-if="column.dataIndex === 'action'">
              <a-popconfirm
                title="确定删除?"
                ok-text="确定"
                cancel-text="取消"
                @confirm="onDelete(record.key)"
              >
                <a href="javascript:;">删除</a>
              </a-popconfirm>
            </template>
          </template>
        </a-table>
      </a-form-item>
      <a-form-item ref="answer" label="正确答案" name="answer">
        <a-input v-model:value="choosedData.answer" />
      </a-form-item>
    </a-form>
  </a-modal>
</template>
<script lang="ts">
import axios from "axios";
import { computed, defineComponent, reactive, Ref, ref, UnwrapRef } from "vue";
import { usePagination } from "vue-request";
import {
  TableState,
  TableStateFilters,
} from "ant-design-vue/lib/table/interface";
import { CheckOutlined, EditOutlined } from "@ant-design/icons-vue";
import { cloneDeep } from "lodash-es";
import { message } from "ant-design-vue";
import { ValidateErrorEntity } from "ant-design-vue/lib/form/interface";
import ENV_URL from "../configs/httpUrl";

const queryData = (params) => {
  return axios.get<APIResult>(`${ENV_URL}/question/info/list?${new URLSearchParams({ question_set_id: 1, ...params })}`);
};
const addData = (params) => {
  return axios.post(ENV_URL + "/question/info/add", { question_set_id: 1, ...params });
};
const editData = (params) => {
  return axios.post(ENV_URL + "/question/info/edit", params);
};
const deleteData = (params) => {
  return axios.post(ENV_URL + "/question/info/del", params);
};
const columns = [
  {
    title: "题目",
    dataIndex: "question_desc",
    width: "20%",
  },
  {
    title: "答案",
    dataIndex: "choice_info",
    width: "20%",
  },
  {
    title: "正确答案",
    dataIndex: "answer",
  },
  {
    title: "操作",
    dataIndex: "action",
  },
];
const columns2 = [
  {
    title: "选项",
    dataIndex: "title",
  },
  {
    title: "内容",
    dataIndex: "content",
  },
  {
    title: "操作",
    dataIndex: "action",
  },
];
const titleArr = ["A", "B", "C", "D"];

type Pagination = TableState["pagination"];
type APIParams = {
  page_size: number;
  page_no?: number;
  sortField?: string;
  sortOrder?: number;
  [key: string]: any;
};
type APIResult = {
  list: {
    question_desc: string;
    choice_info: { title: string; content: string }[];
    answer: string;
  }[];
};

// modal start
interface DataItem {
  question_id?: string;
  question_desc: string;
  choice_info: ChoiceInfoItem[];
  answer: string;
}
interface ChoiceInfoItem {
  key?: string;
  title: string;
  content: string;
}
// modal end
export default defineComponent({
  components: {
    CheckOutlined,
    EditOutlined,
  },
  setup() {
    const visible = ref<boolean>(false);
    const searchStr = ref<string>("");
    const total = ref<number>(0);
    const {
      data: dataSource,
      run,
      loading,
      current,
      pageSize,
    } = usePagination<any>(queryData, {
      defaultParams: [
        {
          page_size: 3,
        },
      ],
      formatResult: (res) => {
        total.value = res.data.data.total_num;
        return res.data.data.list;
      },
      pagination: {
        currentKey: "page_no",
        pageSizeKey: "page_size",
      },
    });

    const pagination = computed(() => ({
      current: current.value,
      pageSize: pageSize.value,
    }));

    const changePage = (page_no) => {
      run({
        page_size: pageSize.value,
        page_no: page_no,
      });
    }

    const handleTableChange = (pag: Pagination, filters: any) => {
      run({
        page_size: pag!.pageSize!,
        page_no: pag?.current,
        ...filters,
      });
    };

    const search = (current) => {
      let page = pagination.value;
      if(current){
      page.current = current;
      }
      handleTableChange(page, { searchStr: searchStr.value });
    };

    // modal start
    const formRef = ref();
    const choosedData: UnwrapRef<DataItem> = reactive({
      question_id: "",
      question_desc: "",
      choice_info: [],
      answer: "",
    });
    const rules = {
      question_desc: [
        { required: true, message: "请输入题目描述", trigger: "change" },
        { max: 25, message: "最多输入25个字符", trigger: "change" },
      ],
      choice_info: [
      ],
      answer: [
        { required: true, message: "请输入正确答案", trigger: "change" },
        { max: 1, message: "最多输入1个字符", trigger: "change" },
      ],
    };
    const count = computed(() => choosedData.choice_info[choosedData.choice_info.length - 1].key + 1);
    const editableData: UnwrapRef<Record<string, ChoiceInfoItem>> = reactive(
      {}
    );

    const edit = (key: string) => {
      editableData[key] = cloneDeep(
        choosedData.choice_info.filter((item) => key === item.key)[0]
      );
    };
    const save = (key: string) => {
      Object.assign(
        choosedData.choice_info.filter((item) => key === item.key)[0],
        editableData[key]
      );
      delete editableData[key];
    };

    const onDelete = (key: string) => {
      choosedData.choice_info = choosedData.choice_info.filter(
        (item) => item.key !== key
      );
    };
    const handleAdd = () => {
      const newData = {
        key: `${count.value}`,
        title: `${count.value}`,
        content: "",
      };
      choosedData.choice_info.push(newData);
    };
    const onSubmit = () => {
      formRef.value.validate().then(() => {
        if (choosedData.choice_info && choosedData.choice_info.length >= 2) {
          let isError = false;
          let errorStr = "";
          let isErrorA = false;
          choosedData.choice_info.forEach((item, index) => {
            if (!item.content || item.content.length > 25) {
              isError = true;
              errorStr += titleArr[index] + "选项内容错误;";
            }
          });
          const titleArrTemp = [];
          for (let i = 0; i < choosedData.choice_info.length; i++) {
            titleArrTemp.push(titleArr[i]);
          }
          if (titleArrTemp.indexOf(choosedData.answer) === -1) {
            isErrorA = true;
          }
          if (isError) {
            message.warning("选项内容为必填项，且最多输入25个字符：" + errorStr);
          } else if (isErrorA) {
            message.warning('正确答案错误');
          } else {
            handleOk(choosedData);
          }
        } else {
          message.warning("请至少输入两个选项，且选项内容为必填项");
        }
      })
        .catch(error => {
          console.log('error', error);
        });;
      // if (!choosedData.question_desc) {
      //   message.warning("请输入题目描述");
      //   return;
      // }
      // if (!choosedData.answer) {
      //   message.warning("请输入正确答案");
      //   return;
      // }
    };
    const handleOk = (e) => {
      const modal = { ...choosedData };
      modal.choice_info.forEach((item, index) => {
        item.title = titleArr[index];
      });
      // console.log(e);
      if (choosedData.question_id) {
        onEdit(e);
      } else {
        onAdd(e);
      }
    };

    // modal end

    // all table start

    const addAll = () => {
      formRef?.value?.resetFields();
      choosedData.question_id = "";
      choosedData.question_desc = "";
      choosedData.choice_info = [
        {
          key: '0',
          title: '0',
          content: '',
        }
      ];
      choosedData.answer = "";
      showModal();
    };
    const editAll = (key, data) => {
      formRef?.value?.resetFields();
      choosedData.question_id = data.question_id;
      choosedData.question_desc = data.question_desc;
      choosedData.choice_info = data.choice_info;
      choosedData.answer = data.answer;
      showModal();
    };

    const showModal = () => {
      visible.value = true;
    };

    const onAdd = (params) => {
      addData(params).then((data: any) => {
        visible.value = false;
        if (data && data.data && data.data.meta.ecode === 0) {
          message.success("新增成功");
          // 刷新数据
          search();
        } else {
          message.error("新增失败：" + data?.data?.meta?.emsg);
        }
      });
    };
    const onEdit = (params) => {
      editData(params).then((data: any) => {
        visible.value = false;
        if (data && data.data && data.data.meta.ecode === 0) {
          message.success("编辑成功");
          // 刷新数据
          search();
        } else {
          message.error("编辑失败：" + data?.data?.meta?.emsg);
        }
      });
    };
    const onDeleteAll = (key) => {
      deleteData({
        question_id: key,
      }).then((data: any) => {
        if (data && data.data && data.data.meta.ecode === 0) {
          message.success("删除成功");
          // 刷新数据
          search();
        } else {
          message.error("删除失败：" + data?.data?.meta?.emsg);
        }
      });
    };

    // all table end

    return {
      dataSource,
      pagination,
      loading,
      columns,
      searchStr,
      search,
      handleTableChange,
      changePage,
      total,
      visible,
      onDelete,
      handleAdd,
      handleOk,
      choosedData,
      editableData,
      count,
      edit,
      save,
      labelCol: { span: 4 },
      wrapperCol: { span: 14 },
      rules,
      formRef,
      onSubmit,
      columns2,
      titleArr,

      addAll,
      editAll,
      onDeleteAll,
    };
  },
});
</script>
<style lang="less">
.search-top {
  margin-bottom: 20px;
}
.list-table {
  margin-bottom: 20px;
}
.editable-cell {
  position: relative;
  .editable-cell-input-wrapper,
  .editable-cell-text-wrapper {
    padding-right: 24px;
  }

  .editable-cell-text-wrapper {
    padding: 5px 24px 5px 5px;
  }

  .editable-cell-icon,
  .editable-cell-icon-check {
    position: absolute;
    right: 0;
    width: 20px;
    cursor: pointer;
  }

  .editable-cell-icon {
    margin-top: 4px;
    display: none;
  }

  .editable-cell-icon-check {
    line-height: 28px;
  }

  .editable-cell-icon:hover,
  .editable-cell-icon-check:hover {
    color: #108ee9;
  }

  .editable-add-btn {
    margin-bottom: 8px;
  }
}
.editable-cell:hover .editable-cell-icon {
  display: inline-block;
}
</style>
